/*
 * @Author: 橘子
 * @Date: 2023/7/9
 * @Project_description: 上传操作
 * @Description: 代码是我抄的，不会也是真的
 */
'use strict'
const qiniu = require("qiniu");
const path = require("path");
const config = require('./config.cicd')
// 生成上传凭证
const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
let configQiniu = new qiniu.conf.Config();
configQiniu.zone = config.zone; // 空间对应的机房
configQiniu.useHttpsDomain = config.useHttpsDomain; // 是否使用https域名
configQiniu.useCdnDomain = config.useCdnDomain; // 上传是否使用cdn加速

/**
 * @Description: 上传
 * @author 橘子
 */
const upload = (url) => {
	//格式化路径，当前目录减去根路径
	let key = path.relative(config.buildPath, url);
	//在windows下替换路径的反斜杠为正斜杠
	key = key.replace(/\\/g, '/');
	//拼接上传路径
	const scopePath = config.scopePath ? config.scopePath + key : key;

	const options = {
		scope: config.scope + ':' + scopePath
	}
	const putPolicy = new qiniu.rs.PutPolicy(options);
	const uploadToken = putPolicy.uploadToken(mac);
	// 生成上传凭证
	const formUploader = new qiniu.form_up.FormUploader(configQiniu);
	const putExtra = new qiniu.form_up.PutExtra();
	return new Promise((resolve, reject) => {
		// 文件上传
		formUploader.putFile(uploadToken, scopePath, url, putExtra, function(respErr, respBody, respInfo) {
			if (respErr) {
				resolve(false);
				console.log('上传失败', respErr)
			}
			if (respInfo.statusCode === 200) {
				resolve(true);
			} else {
				resolve(false);
				console.log('上传失败', respBody, url, 'url')
			}
		});
	});

}


/**
 * @Description: 分批上传
 * @author 橘子
 */
const uploadList = async (list = []) => {
	//分批上传的个数
	let bachNum = config.batchNum
	//分批上传的次数
	let bachCount = Math.ceil(list.length / bachNum)
	let errorsList = []
	for (let i = 0; i < bachCount; i++) {
		//分批上传的数组
		let bachList = list.slice(i * bachNum, (i + 1) * bachNum)
		let taskList = []
		bachList.forEach(item => {
			taskList.push(upload(item))
		})
		let res = await Promise.all(taskList)
		//res是一个数组。里面是true和false,我需要记录返回false的文件
		res.forEach((item, index) => {
			if (!item) errorsList.push(bachList[index])
		})
		console.log(`第${i + 1}批上传成功${res.length}个文件`)
	}
	return errorsList

}
/**
 * @Description: 单个上传
 * @author 橘子
 */
const uploadSingle = async (list = []) => {
	let errorsList = []
	for (let i = 0; i < list.length; i++) {
		const res = await upload(list[i])
		if (!res) {
			console.log('第' + (i + 1) + '个文件上传失败')
			errorsList.push(list[i])
		} else {
			console.log('第' + (i + 1) + '个文件上传成功')
		}
	}
	if (errorsList.length > 0) {
		console.log('总共有' + errorsList.length + '个文件上传失败')
	}
	return errorsList
}

module.exports = {
	upload,
	uploadList,
	uploadSingle
}